package org.geostats;

import static org.geoscrape.util.ParamParser.getParameter;

import java.io.IOException;
import java.util.HashMap;
import java.util.Random;

import org.geoscrape.Cacher;
import org.geoscrape.Login;

/**
 * Picks a number of members at random, calculates estimated number of premium
 * members.
 * 
 */
public class MemberSurveyor
{

	/**
	 * @param args
	 * @throws IOException
	 */
	public static void main(String[] args) throws IOException
	{

		String name = getParameter("n", args);
		String password = getParameter("p", args);
		Login login = new Login(name, password);
		login.authenticate();
		int maxMemberId = 5050000;
		int sampleSize = 1000;
		Random rand = new Random();
		HashMap<String, Boolean> known = new HashMap<String, Boolean>();
		while (known.keySet().size() < sampleSize)
		{
			int id = rand.nextInt(maxMemberId) + 1;
			String idString = Integer.toString(id);
			if (known.get(idString) == null)
			{
				Cacher c = new Cacher(new Long(id));
				c.populate(login);
				if (c.isPremiumMember() != null)
				{
					known.put(idString, c.isPremiumMember());
				}
			}
		}
		int premiumCount = 0;
		for (String key : known.keySet())
		{
			if (known.get(key))
			{
				premiumCount++;
			}
		}
		double population = maxMemberId;
		double ratio = premiumCount / (double)sampleSize;

		double pf = (population - sampleSize) / (population - 1.0);
		// 95% confidence level
		double z = 3.8416;
		double conInt = Math.sqrt(z * pf * ratio * (1 - ratio) / sampleSize) * 100;
		ratio *= 100;
		System.out.println(ratio + "% premium members,  \u00B1" + conInt
				+ "%, 95% confidence level.");
	}
}
